package com.bfly.mall.wechat.api;

import com.alibaba.fastjson.JSONObject;
import com.bfly.common.ResponseUtil;
import com.bfly.core.base.entity.ResponseData;
import com.bfly.mall.wechat.mp.service.message.WeChatMpMsgFactory;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 微信公众号Controller
 *
 * @author 长沙商脉科技有限公司
 * @date 2021/1/7 18:37
 */
@RestController("WeChatMpApiController")
@RequestMapping(value = "/wechat/push")
public class WeChatMpController {

    private Logger logger = LoggerFactory.getLogger(WeChatMpController.class);

    /**
     * 微信支付完成回调--微信回调接口可能会有延时，或系统出现异常的情况
     * 系统不管成功支付与否，统一返回SUCCESS，订单支付状态通过系统的定时轮询机制
     * 主动去查询微信订单交易情况进行对单
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/12/4 10:43
     */
    @PostMapping(value = "/payed/callback")
    public void orderPayCompleteCallBack(HttpServletResponse response) {
        JSONObject json = new JSONObject();
        json.put("code", "SUCCESS");
        json.put("message", "");
        ResponseUtil.writeJson(response, ResponseData.getSuccess(json));
    }

    /**
     * 注册开发者配置服务器验证token
     *
     * @author 长沙商脉科技有限公司
     * @date 2021/1/7 19:19
     */
    @GetMapping(value = "")
    public void verifyToken(HttpServletResponse response, HttpServletRequest request) {
        String echoStr = request.getParameter("echostr");            // 随机字符串
        ResponseUtil.writeText(response, echoStr);
    }

    /**
     * 接收微信服务器发过来的信息
     *
     * @author 长沙商脉科技有限公司
     * @date 2021/1/7 19:14
     */
    @PostMapping(value = "")
    public void receiveMessageFromWeChat(HttpServletResponse response, HttpServletRequest request) throws Exception {
        String xml = IOUtils.toString(request.getReader());
        xml = WeChatMpMsgFactory.execute(xml);
        if (StringUtils.isNotBlank(xml)) {
            ResponseUtil.writeXml(response, xml);
            logger.info("回复微信公众号消息成功:" + xml);
        } else {
            ResponseUtil.writeText(response, "");
        }
    }
}